﻿using System.Reflection;
using FileEfCore.DbContexts;
using FileServer.Core.Server;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace FileServer.Core;

public class InitFileServerHostedService : IHostedService
{
    private readonly IFileServerListener _fileServerListener;
    private readonly IServiceProvider _serviceProvider;

    public InitFileServerHostedService(IFileServerListener fileServerListener,
        IServiceProvider serviceProvider)
    {
        _fileServerListener = fileServerListener;
        _serviceProvider = serviceProvider;
    }

    public async Task StartAsync(CancellationToken cancellationToken)
    {
        Console.WriteLine(@"                                              
______ _ _      _____                          
|  ___(_) |    /  ___|                         
| |_   _| | ___\ `--.  ___ _ ____   _____ _ __ 
|  _| | | |/ _ \`--. \/ _ \ '__\ \ / / _ \ '__|
| |   | | |  __/\__/ /  __/ |   \ V /  __/ |   
\_|   |_|_|\___\____/ \___|_|    \_/ \___|_|   
            ");
        InitializeDb();
        var version = Assembly.GetExecutingAssembly().GetName().Version;
        var ver = $"{version.Major}.{version.Minor}.{version.Build}";
        Console.WriteLine($" :: FileServer ::        {ver}");
        await _fileServerListener.Listen();
    }

    private void InitializeDb()
    {
        var context = _serviceProvider.GetRequiredService<ServerFileDbContext>();
        context.Database.EnsureCreated();
    }

    public async Task StopAsync(CancellationToken cancellationToken)
    {
        _fileServerListener.Dispose();
    }
}